package mvc.gui.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.swing.filechooser.FileFilter;

public class SimpleFileFilter extends FileFilter {
	private List<String> acceptedExtensions;

	public SimpleFileFilter() {
	}

	public SimpleFileFilter(List<String> sl) {
		this.setAcceptedFileExtensions(sl);
	}
	public SimpleFileFilter(String sl) {
		acceptedExtensions = new ArrayList<String>();
		this.acceptedExtensions.add(sl.toLowerCase());
	}

	private void setAcceptedFileExtensions(List<String> sl) {
		acceptedExtensions = new ArrayList<String>(sl.size());
		for (String s : sl) {
			acceptedExtensions.add(s.toLowerCase());
		}
	}

	/*
	 * Copy of method from
	 * http://java.sun.com/docs/books/tutorial/uiswing/examples
	 * /components/FileChooserDemo2Project/src/components/Utils.java
	 */
	private static String getExtension(File f) {
		String ext = null;
		String s = f.getName();
		int i = s.lastIndexOf('.');

		if (i > 0 && i < s.length() - 1) {
			ext = s.substring(i + 1).toLowerCase();
		}
		return ext;
	}

	@Override
	public boolean accept(File arg0) {
		if (arg0.isDirectory()
				|| (acceptedExtensions != null && acceptedExtensions
						.contains(getExtension(arg0)))) {
			return true;
		}
		return false;
	}

	public String getFileFilterExtension() {
		return acceptedExtensions.get(0);
	}

	@Override
	public String getDescription() {
		return acceptedExtensions.toString();
	}

}
